/*
 * @Description: 归集弹窗
 * @Author: Rfan
 * @Date: 2022-04-29 09:39:40
 * @LastEditTime: 2022-05-27 18:34:36
 */

import { Key, useEffect, useState } from 'react';
import { Button, Form, Input, Modal, Select, Space } from 'antd';
import { appState } from '@/store/mobx';
import { fetchATListByFondId } from '@/api/archivesType';
import { fetchFondsListByUnitId } from '@/api/fonds';
import { selectItemByKey } from '@/utils/list';
import { useBatchManageContext } from '../../contexts/BatchManageContext';
import type { ICommonDialog } from '@/interfaces/global';

const { Option } = Select;

interface CreateBatchDialogProps extends ICommonDialog {
  data?: any;
}

const CreateBatchDialog = (props: CreateBatchDialogProps) => {
  const { visible, data, onClose } = props;
  const { selectReceiveType, receiveTypeList, receiveModeList, addBatchFunc } =
    useBatchManageContext();
  const [fondList, setFondList] = useState([]);
  const [atList, setAtList] = useState([]);
  const [atLoading, setAtLoading] = useState(false);
  const [selectAT, setSelectAT] = useState(atList[0] || {});
  const [form] = Form.useForm();

  useEffect(() => {
    if (visible) {
      fetchFondsListByUnitId(appState.unitId).then((res) => {
        const fondList = res.data || [];
        setFondList(fondList);
      });
      data
        ? form.setFieldsValue(data)
        : form.setFieldsValue({
            receiveMode: 0,
            receiveType: selectReceiveType
          });
    }
  }, [visible]);

  /**
   * @description: 关闭弹窗
   */
  const onCancel = () => {
    onClose();
  };

  /**
   * @description 切换全宗方法
   * @param {any} value 切换的全宗ID
   * @return {*}
   */
  const handleFondChange = (value: Key): void => {
    console.log('fond', value);
    setAtLoading(true);
    fetchATListByFondId(value)
      .then((res) => {
        setAtList(res.data);
        res.data.length > 0 && setSelectAT(res.data[0]);
      })
      .finally(() => {
        setAtLoading(false);
      });
  };

  /**
   * @description 切换档案类型方法
   * @param {Key} value 切换的档案类型ID
   */
  const onATChange = (value: Key) => {
    setSelectAT(selectItemByKey(value, atList));
  };

  /**
   * @description 提交表单，触发onFinish方法
   */
  const submitFunc = () => {
    form.submit();
  };

  // 新增批次方法
  const onFinish = (values: any) => {
    const params = { ...values };
    addBatchFunc(params).then(() => {
      onCancel();
    });
  };

  return (
    <Modal
      title="创建批次"
      visible={visible}
      width={450}
      destroyOnClose
      onCancel={onCancel}
      footer={[
        <Button key="close" onClick={onCancel}>
          关闭
        </Button>,
        <Button
          key="save"
          type="primary"
          onClick={() => {
            submitFunc();
          }}
        >
          完成
        </Button>
      ]}
    >
      <Form
        labelCol={{ span: 6 }}
        wrapperCol={{ span: 16 }}
        preserve={false}
        form={form}
        onFinish={onFinish}
      >
        <Form.Item name="receiveMode" label="接收类型">
          <Select disabled>
            {receiveModeList.map((item: any) => (
              <Option key={item.id} value={item.id}>
                {item.name}
              </Option>
            ))}
          </Select>
        </Form.Item>
        <Form.Item name="name" label="批次名称">
          <Input />
        </Form.Item>
        <Form.Item name="receiveType" label="数据包类型">
          <Select>
            {receiveTypeList.map((item: any) => (
              <Option key={item.id} value={item.id}>
                {item.name}
              </Option>
            ))}
          </Select>
        </Form.Item>
        <Form.Item label="档案类型">
          <Space>
            <Form.Item name="fondsId" noStyle>
              <Select placeholder="请选择全宗" style={{ width: 120 }} onChange={handleFondChange}>
                {fondList.map((fond) => (
                  <Option key={fond.id}>{fond.fondName}</Option>
                ))}
              </Select>
            </Form.Item>
            <Form.Item name="archiveTypeId" noStyle>
              <Select
                value={selectAT?.id}
                loading={atLoading}
                placeholder="请选择档案类型"
                style={{ width: 120 }}
                onChange={onATChange}
              >
                {atList.map((item: any) => (
                  <Option key={item.id} value={item.id}>
                    {item.atName}
                  </Option>
                ))}
              </Select>
            </Form.Item>
          </Space>
        </Form.Item>
        <Form.Item name="transferUnit" label="来源单位">
          <Input />
        </Form.Item>
        <Form.Item name="transferUnit" label="移交人">
          <Input />
        </Form.Item>
        <Form.Item name="transferUnit" label="移交载体类型">
          <Input />
        </Form.Item>
        <Form.Item name="transferUnit" label="移交载体规格">
          <Input />
        </Form.Item>
      </Form>
    </Modal>
  );
};

export default CreateBatchDialog;
